<template>
  <div class="drama-list-container">
    <div class="header">
      <h2 class="page-title">首页</h2>
      <el-button v-if="dramaList.length > 0" color="#1c1d29" @click="handleCreateClick"
        class="custom-operate-btn">创建剧本</el-button>
    </div>

    <div v-loading="loading" class="drama-cards-container">
      <div v-if="dramaList.length === 0 && !loading" class="empty-state">
        <img src="@/assets/images/empty.png" class="empty-image" alt="暂无剧本" />
        <p class="empty-text">暂无剧本，快点击按钮创建吧</p>
        <el-button color="#1c1d29" @click="handleCreateClick">创建剧本</el-button>
      </div>
      <div v-else class="drama-cards-grid">
        <el-card v-for="item in dramaList" :key="item.dramaId" class="drama-card" shadow="hover"
          @click="handleView(item)">
          <img :src="item.coverImageUrl" class="drama-card-cover-image" />
          <div class="drama-card-content">
            <h3 class="drama-name">{{ item.dramaName }}</h3>
            <div class="drama-creator">
              <span>成员: {{ item.createUser }}</span>
            </div>
            <div class="drama-card-actions">
              <div class="action-btn" @click.stop="handleEdit(item)">剧集生产</div>
              <div class="action-divider"></div>
              <div class="action-btn" @click.stop="handleEditInfo(item)">编辑信息</div>
              <template v-if="userInfo.role === 'ADMIN' || userInfo.role === 'SUPER_ADMIN'">
                <div class="action-divider"></div>
                <div class="action-btn" @click.stop="handlePermission(item)">项目成员</div>
              </template>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- <div v-if="dramaList.length > 0" class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div> -->

    <!-- 创建剧本弹窗 -->
    <el-dialog v-model="dialogVisible" title="创建剧本" width="680px" :close-on-click-modal="false"
      :before-close="handleDialogClose" custom-class="drama-dialog">
      <template #header>
        <div class="dialog-title">{{ editDramaId ? '修改' : '创建' }}剧本</div>
      </template>
      <el-form :model="createForm" label-position="top" v-loading="uploadLoading">
        <el-form-item>
          <template #label>
            <span class="form-label">剧名<span class="required-mark">*</span></span>
          </template>
          <el-input v-model="createForm.dramaName" placeholder="请输入" maxlength="50" show-word-limit />
        </el-form-item>

        <el-form-item>
          <template #label>
            <span class="form-label">描述</span>
          </template>
          <el-input v-model="createForm.dramaDesc" type="textarea" :rows="3" placeholder="请输入" maxlength="200"
            show-word-limit />
        </el-form-item>

        <!-- <el-form-item>
          <template #label>
            <span class="form-label">项目成员<span class="required-mark">*</span></span>
          </template>
          <el-select
            v-model="createForm.members"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词搜索成员"
            :remote-method="remoteSearchMembers"
            :loading="memberLoading"
            style="width: 100%"
          >
            <el-option
              v-for="item in memberOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->

        <el-form-item>
          <template #label>
            <span class="form-label">图片<span class="required-mark">*</span></span>
          </template>
          <div class="cover-upload-container">
            <PicUpload @start="beforeCoverUpload" @finish="handleCoverUpload" :defaultUrl="createForm.coverUrl" />
          </div>
        </el-form-item>

        <!-- 新增的四个参数 - 第一行 -->
        <div class="form-row" style="margin: 0;">
          <el-form-item class="form-item-half">
            <template #label>
              <span class="form-label">图片素材尺寸<span class="required-mark">*</span></span>
            </template>
            <el-select v-model="createForm.imageSize" placeholder="请选择" style="width: 100%">
              <el-option label="9:16" value="9:16" />
              <el-option label="16:9" value="16:9" />
              <el-option label="4:3" value="4:3" />
              <el-option label="1:1" value="1:1" />
              <el-option label="3:4" value="3:4" />
              <el-option label="21:9" value="21:9" />
            </el-select>
          </el-form-item>

          <el-form-item class="form-item-half">
            <template #label>
              <span class="form-label">视频素材尺寸<span class="required-mark">*</span></span>
            </template>
            <el-select v-model="createForm.videoSize" placeholder="请选择" style="width: 100%">
              <el-option label="9:16" value="9:16" />
              <el-option label="16:9" value="16:9" />
              <el-option label="4:3" value="4:3" />
              <el-option label="1:1" value="1:1" />
              <el-option label="3:4" value="3:4" />
              <el-option label="21:9" value="21:9" />
            </el-select>
          </el-form-item>
        </div>

        <!-- 新增的四个参数 - 第二行 -->
        <div class="form-row" style="margin: 0;">
          <el-form-item class="form-item-half">
            <template #label>
              <span class="form-label">视频素材分辨率<span class="required-mark">*</span></span>
            </template>
            <el-select v-model="createForm.resolution" placeholder="请选择" style="width: 100%">
              <el-option label="1080p" value="1080p" />
              <el-option label="720p" value="720p" />
              <el-option label="480p" value="480p" />
            </el-select>
          </el-form-item>

          <el-form-item class="form-item-half">
            <template #label>
              <span class="form-label">视频素材fps<span class="required-mark">*</span></span>
            </template>
            <el-select v-model="createForm.fps" placeholder="请选择" style="width: 100%">
              <el-option label="16" value="16" />
              <el-option label="24" value="24" />
            </el-select>
          </el-form-item>
        </div>

        <el-form-item>
          <template #label>
            <span class="form-label">上传剧本<span class="required-mark">*</span></span>
          </template>
          <div class="cover-upload-container">
            <el-upload v-if="!editDramaId" class="drama-file-uploader" :show-file-list="false"
              :before-upload="beforeDramaUpload" :http-request="handleDramaUpload" drag accept=".pdf">
              <div class="file-upload-placeholder">
                <img src="@/assets/images/download.png" class="file-upload-icon" />
                <div class="file-upload-text">点击或将文件拖拽到这里上传</div>
                <div class="file-upload-tip">支持 pdf，大小不超过 200 MB</div>
              </div>
            </el-upload>
            <div class="drama-file-preview" v-if="createForm.dramaUrl || editDramaId">
              <img src="@/assets/images/ppt.png" class="drama-file-icon" />
              <div class="drama-file-name" v-if="!editDramaId">{{ createForm.dramaUrl }}</div>
              <div class="drama-file-name" v-else>{{ createForm.dramaName }}.pdf</div>
              <div class="drama-remove-btn">
                <div class="drama-file-size">{{ (createForm.fileSize / 1024 / 1024).toFixed(2) }}M</div>
                <el-icon color="#95999E" v-if="!editDramaId" @click.stop="removeDrama">
                  <Close />
                </el-icon>
              </div>
            </div>
            <CircleProgress v-if="uploadDramaLoading" :percentage="75" type="line" :indeterminate="true" :width="200"
              :stroke-width="3" :duration="800" />
          </div>
        </el-form-item>

        <el-form-item>
          <template #label>
            <span class="form-label">绑定模型ID<span class="required-mark">*</span></span>
          </template>
          <el-input v-model="createForm.profile" :disabled="editDramaId" placeholder="请输入模型ID" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button v-if="isEditMode" class="save-el-button"
            style="background: #fff;border-color: #FC3333 !important;color: #FC3333;border-radius: 8px;"
            @click="handleDeleteFromDialog">
            删除
          </el-button>
          <div class="flex-spacer"></div>
          <el-button class="save-el-button"
            style="background: #fff;border:1px solid #F0F2F5;color: #1F2329;border-radius: 8px;"
            @click="handleDialogClose">取消</el-button>
          <el-button color="#1c1d29" class="save-el-button" @click="handleCreateSubmit" :loading="createLoading">
            {{ isEditMode ? '保存' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 剧本权限弹窗 -->
    <el-dialog v-model="permissionDialogVisible" title="剧本权限管理" width="800px" :close-on-click-modal="false"
      custom-class="permission-dialog">
      <template #header>
        <div class="dialog-title">项目成员管理</div>
      </template>

      <div v-loading="permissionLoading" class="permission-content">
        <div class="permission-header">
          <el-input v-model="userSearchQuery" placeholder="搜索并添加" @input="handleUserSearch" style="width: 240px"
            :prefix-icon="Search" clearable />
          <div class="permission-user-list" v-if="userList.length > 0 || isEmpty">
            <div v-loading="userSearchLoading" class="user-list">
              <div v-for="user in userList" :key="user.userId" class="user-item"
                :class="{ selected: selectedUserIds.includes(user.userId) }" @click="toggleUserSelection(user)">
                <div class="user-info">
                  <span class="user-nickname">{{ user.nickname || user.username }}</span>
                </div>
              </div>
              <div v-if="userList.length === 0 && !userSearchLoading" class="no-users">
                暂无结果
              </div>
            </div>
          </div>
        </div>

        <div class="permission-list">
          <!-- 用户权限列表 -->
          <el-table v-if="permissionList.length > 0" :data="permissionList" style="width: 100%" border>
            <el-table-column prop="userNickname" label="用户" width="288" />
            <el-table-column prop="userId" label="账号" width="288" />

            <el-table-column label="操作" width="56">
              <template #default="{ row }">
                <span class="txt-btn" @click="handleRevokePermission(row)">删除</span>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="permissionList.length === 0 && !permissionLoading" class="no-permissions">
            <img src="@/assets/images/empty.png" class="empty-image" alt="暂无角色" />
            <p class="empty-text">暂无团队成员</p>
          </div>
        </div>
      </div>

      <template #footer v-if="!(permissionList.length === 0 && !permissionLoading)">
        <span>
          <el-button @click="closePermissionDialog" color="#1c1d29">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDramaList, deleteDrama, createDrama, uploadFile, updateDrama, getDramaPermissions, grantPermission, revokePermission, searchUsers } from '@/api/drama'
import { Upload, Document, Delete, Plus, Close, Search } from '@element-plus/icons-vue'
import CircleProgress from '@/components/common/CircleProgress.vue'
import PicUpload from '@/components/common/PicUpload.vue'
import { useUserStore } from '@/store/user'

// 用户信息
const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)
const router = useRouter()
const dramaList = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(1000)
const uploadCoverLoading = ref(false)

// 剧本权限相关
const permissionDialogVisible = ref(false)
const permissionLoading = ref(false)
const permissionList = ref([])
const currentPermissionDrama = ref(null)
const grantingUserIds = ref([])
const revokingUserIds = ref([])

// 用户搜索相关
const userSearchDialogVisible = ref(false)
const userSearchLoading = ref(false)
const userList = ref([])
const userSearchQuery = ref('')
const selectedUserIds = ref([])
const grantingUsers = ref(false)

// 创建剧本弹窗相关
const dialogVisible = ref(false)
const createLoading = ref(false)
const memberLoading = ref(false)
const uploadLoading = ref(false)
const uploadDramaLoading = ref(false) // 添加剧本上传loading状态
const memberOptions = ref([
  { value: '张三', label: '张三' },
  { value: '李四', label: '李四' },
  { value: '王五', label: '王五' }
])

const createForm = reactive({
  dramaName: '',
  dramaDesc: '',
  members: [],
  cover: null,
  coverUrl: '',
  dramaFile: null,
  dramaUrl: '',
  coverResKey: '',
  dramaResKey: '',
  profile: '', // Adding new profile field
  fileUrl: '', // Added fileUrl field
  imageSize: '9:16', // Added image size
  videoSize: '9:16', // Added video size
  resolution: '1080p', // Added resolution
  fps: '24', // Added fps
  fileSize: 0
})

// 搜索成员
const remoteSearchMembers = (query) => {
  if (query) {
    memberLoading.value = true
    setTimeout(() => {
      memberLoading.value = false
      memberOptions.value = [
        { value: '张三', label: '张三' },
        { value: '李四', label: '李四' },
        { value: '王五', label: '王五' }
      ].filter(item => item.label.includes(query))
    }, 200)
  } else {
    memberOptions.value = [
      { value: '张三', label: '张三' },
      { value: '李四', label: '李四' },
      { value: '王五', label: '王五' }
    ]
  }
}

// 封面上传前验证
const beforeCoverUpload = (file) => {
  createLoading.value = true
}

// 剧本上传前验证
const beforeDramaUpload = (file) => {
  const isPDF = file.type === 'application/pdf'
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isPDF) {
    ElMessage.error('只能上传PDF文件!')
    return false
  }

  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }

  return true
}

// 处理封面上传
const handleCoverUpload = async (fileKey) => {
  try {
    createForm.coverResKey = fileKey
    createLoading.value = false
  } catch (error) {
    createLoading.value = false
  }
}

// 处理剧本上传
const handleDramaUpload = async (options) => {
  const file = options.file
  const isPdf = file.type === 'application/pdf' || file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || file.type === 'application/msword'
  if (!isPdf) {
    ElMessage.error('只能上传PDF,WORD文件!')
    return
  }

  // 设置上传状态
  uploadDramaLoading.value = true
  createLoading.value = true

  try {
    // 保存文件对象和名称用于显示
    createForm.dramaFile = file
    createForm.dramaUrl = file.name
    // 上传文件获取fileKey
    const res = await uploadFile(file)
    if (res.data && res.data.fileKey) {
      createForm.dramaResKey = res.data.fileKey
      uploadLoading.value = false
      createLoading.value = false
      createForm.fileSize = file.size
      ElMessage.success('剧本文件上传成功')
    } else {
      uploadLoading.value = false
      createLoading.value = false
      throw new Error('上传失败')
    }
  } catch (error) {
    createLoading.value = false
    uploadLoading.value = false
    console.error('剧本上传失败:', error)
    ElMessage.error('剧本文件上传失败')
  } finally {
    uploadDramaLoading.value = false
    createLoading.value = false
  }
}

// 移除已上传剧本
const removeDrama = () => {
  createForm.dramaUrl = ''
  createForm.dramaFile = null
  createForm.dramaResKey = ''
  ElMessage.success('已移除剧本文件')
}

// 关闭弹窗
const handleDialogClose = () => {
  // 关闭弹窗
  dialogVisible.value = false

  // 重置表单数据
  resetCreateForm()

  // 重置编辑状态
  isEditMode.value = false
  editDramaId.value = null
}

// 重置创建表单
const resetCreateForm = () => {
  // 重置基本字段
  createForm.dramaName = ''
  createForm.dramaDesc = ''
  createForm.members = []

  // 重置封面相关字段
  createForm.cover = null
  createForm.coverUrl = ''
  createForm.coverResKey = ''

  // 重置剧本文件相关字段
  createForm.dramaFile = null
  createForm.dramaUrl = ''
  createForm.dramaResKey = ''
  createForm.fileUrl = ''

  // 重置其他字段
  createForm.profile = ''
  createForm.imageSize = '9:16'
  createForm.videoSize = '9:16'
  createForm.resolution = '1080p'
  createForm.fps = '24'

  // 重置上传状态
  uploadCoverLoading.value = false
  uploadDramaLoading.value = false
}

// 创建剧本提交
const handleCreateSubmit = async () => {
  // 表单验证
  if (!createForm.dramaName) {
    ElMessage.warning('请输入剧本名称')
    return
  }

  // if (createForm.members.length === 0) {
  //   ElMessage.warning('请选择项目成员')
  //   return
  // }

  if (!isEditMode.value && !createForm.coverResKey) {
    ElMessage.warning('请上传剧本背景图')
    return
  }

  if (!createForm.profile) {
    ElMessage.warning('请输入模型ID')
    return
  }

  // 验证新增的必填字段
  if (!createForm.imageSize) {
    ElMessage.warning('请选择图片素材尺寸')
    return
  }

  if (!createForm.videoSize) {
    ElMessage.warning('请选择视频素材尺寸')
    return
  }

  if (!createForm.resolution) {
    ElMessage.warning('请选择视频素材分辨率')
    return
  }

  if (!createForm.fps) {
    ElMessage.warning('请选择视频素材fps')
    return
  }

  createLoading.value = true

  try {
    // 创建请求数据对象
    const dramaData = {
      dramaName: createForm.dramaName,
      dramaDesc: createForm.dramaDesc,
      createUser: createForm.members.join(','),
      coverResKey: createForm.coverResKey,
      profile: createForm.profile, // Add new profile field
      imageSize: createForm.imageSize, // Add new image size field
      videoSize: createForm.videoSize, // Add new video size field
      resolution: createForm.resolution, // Add new resolution field
      fps: createForm.fps // Add new fps field
    }

    // 添加剧本fileKey（如果有）
    if (createForm.dramaResKey) {
      dramaData.dramaResKey = createForm.dramaResKey
    }

    if (isEditMode.value) {
      // 编辑模式
      dramaData.dramaId = editDramaId.value
      await updateDrama(dramaData)
      ElMessage.success('剧本更新成功')
    } else {
      // 创建模式
      await createDrama(dramaData)
      ElMessage.success('剧本创建成功')
    }

    dialogVisible.value = false
    resetCreateForm()
    fetchDramaList()
  } catch (error) {
    console.error(isEditMode.value ? '更新剧本失败:' : '创建剧本失败:', error)
    ElMessage.error(isEditMode.value ? '更新剧本失败' : '创建剧本失败')
  } finally {
    createLoading.value = false
    isEditMode.value = false
    editDramaId.value = null
  }
}

// 处理"创建剧本"按钮点击
const handleCreateClick = () => {
  // 重置表单数据
  resetCreateForm()

  // 重置编辑状态
  isEditMode.value = false
  editDramaId.value = null

  // 打开弹窗
  dialogVisible.value = true
}

const searchForm = reactive({
  dramaName: '',
  companyName: ''
})

// 格式化价格，将分转为元并添加千分位分隔符
const formatPrice = (price) => {
  if (!price && price !== 0) return '--'
  // 将分转换为元
  const yuan = (price / 100).toFixed(2)
  // 添加千分位分隔符
  return '¥' + yuan.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '--'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).replace(/\//g, '-')
}

// 获取剧本列表
const fetchDramaList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    }

    const res = await getDramaList(params)
    if (res.data) {
      dramaList.value = res.data.list || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取剧本列表失败:', error)
    ElMessage.error('获取剧本列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchDramaList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  currentPage.value = 1
  fetchDramaList()
}

// 页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchDramaList()
}

// 每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchDramaList()
}

// 查看剧本
const handleView = (row) => {
  router.push(`/drama/detail/${row.dramaId}`)
}

// 编辑剧本
const handleEdit = (row) => {
  router.push(`/drama/edit/${row.dramaId}`)
}

// 编辑剧本信息
const handleEditInfo = (row) => {
  // 填充表单数据
  createForm.dramaName = row.dramaName
  createForm.dramaDesc = row.dramaDesc || ''
  createForm.members = row.createUser ? row.createUser.split(',') : []
  createForm.coverUrl = row.coverImageUrl
  createForm.coverResKey = row.coverResKey || ''
  createForm.profile = row.profile || '' // Fill new profile field
  createForm.fileUrl = row.fileUrl || '' // Fill new profile field
  createForm.imageSize = row.imageSize || '9:16' // Fill new image size field
  createForm.videoSize = row.videoSize || '9:16' // Fill new video size field
  createForm.resolution = row.resolution || '1080p' // Fill new resolution field
  createForm.fps = row.fps || '24' // Fill new fps field
  createForm.fileSize = row.fileSize || '24' // Fill new fps field

  // 设置编辑模式
  isEditMode.value = true
  editDramaId.value = row.dramaId

  // 打开弹窗
  dialogVisible.value = true
}

// 从弹窗中删除剧本
const handleDeleteFromDialog = () => {
  if (!editDramaId.value) return

  ElMessageBox.confirm(`删除后不可恢复，确认删除吗？`, '', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: '',
    closeIcon: 'add',
    customClass: 'delete-confirm-dialog',
    confirmButtonClass: 'confirm-delete-btn-class',
    cancelButtonClass: 'cancel-delete-btn-class'
  }).then(async () => {
    try {
      await deleteDrama(editDramaId.value)
      ElMessage.success('删除成功')
      dialogVisible.value = false
      resetCreateForm()
      isEditMode.value = false
      editDramaId.value = null
      fetchDramaList()
    } catch (error) {
      console.error('删除剧本失败:', error)
      ElMessage.error('删除剧本失败')
    }
  }).catch(() => { })
}

// 剧本权限相关方法
// 打开权限弹窗
const handlePermission = (drama) => {
  currentPermissionDrama.value = drama
  permissionDialogVisible.value = true
  fetchPermissionList(drama.dramaId)
}

// 获取权限列表
const fetchPermissionList = async (dramaId) => {
  permissionLoading.value = true
  try {
    const res = await getDramaPermissions(dramaId)
    permissionList.value = res.data || []
  } catch (error) {
    console.error('获取权限列表失败:', error)
    ElMessage.error('获取权限列表失败')
  } finally {
    permissionLoading.value = false
  }
}


// 撤销权限
const handleRevokePermission = async (permission) => {
  revokingUserIds.value.push(permission.userId)
  try {
    await revokePermission({
      userId: permission.userId,
      dramaId: permission.dramaId
    })

    ElMessage.success('删除成功')
    fetchPermissionList(permission.dramaId)
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error(error.message)
  } finally {
    const index = revokingUserIds.value.indexOf(permission.userId)
    if (index > -1) {
      revokingUserIds.value.splice(index, 1)
    }
  }
}

// 用户搜索相关方法
// 处理用户搜索输入
const handleUserSearch = () => {
  if (!userSearchQuery.value.trim()) {
    userList.value = []
    isEmpty.value = false
  } else {
    handleSearchUsers(userSearchQuery.value)
  }
}

const isEmpty = ref(false)
// 搜索用户
const handleSearchUsers = async (query) => {
  userSearchLoading.value = true
  try {
    const res = await searchUsers({ query })
    userList.value = res.data || []
    isEmpty.value = userList.value.length === 0
  } catch (error) {
    console.error('搜索用户失败:', error)
    ElMessage.error('搜索用户失败')
    userList.value = []
  } finally {
    userSearchLoading.value = false
  }
}

// 切换用户选择
const toggleUserSelection = (user) => {
  const index = selectedUserIds.value.indexOf(user.userId)
  if (index > -1) {
    selectedUserIds.value.splice(index, 1)
  } else {
    selectedUserIds.value.push(user.userId)
  }
  confirmGrantPermissions()
}

// 确认授权权限
const confirmGrantPermissions = async () => {
  if (selectedUserIds.value.length === 0) {
    ElMessage.warning('请选择要授权的用户')
    return
  }

  grantingUsers.value = true
  const dramaId = currentPermissionDrama.value.dramaId

  try {
    try {
      await grantPermission({
        userIds: selectedUserIds.value,
        dramaId: dramaId,
        permissionType: 'EDIT'
      })
    } catch (error) {
      console.error(`授权失败`, error)
    }

    ElMessage.success(`授权成功`)
    isEmpty.value = false
    userSearchQuery.value = ''
    fetchPermissionList(dramaId)
    closeUserSearchDialog()
  } catch (error) {
    console.error('批量授权失败:', error)
    ElMessage.error('批量授权失败')
  } finally {
    grantingUsers.value = false
  }
}

// 关闭用户搜索弹窗
const closeUserSearchDialog = () => {
  userSearchDialogVisible.value = false
  userList.value = []
  userSearchQuery.value = ''
  selectedUserIds.value = []
}

// 关闭权限弹窗
const closePermissionDialog = () => {
  permissionDialogVisible.value = false
  permissionList.value = []
  currentPermissionDrama.value = null
  grantingUserIds.value = []
  revokingUserIds.value = []
}

// 在script setup的顶部添加这些变量
const isEditMode = ref(false)
const editDramaId = ref(null)

onMounted(() => {
  fetchDramaList()
})
</script>

<style scoped>
.empty-image {
  width: 240px;
  margin: auto;
  height: 240px;
}

.empty-text {
  font-size: 14px;
  color: #787C8F;
  margin: 20px 0;
}

.drama-list-container {
  padding: 20px;
}

.drama-file-size {
  font-size: 12px;
  color: #95999E;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.drama-cards-container {
  min-height: 200px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 186px;
}

.empty-image {
  width: 240px;
  height: 240px;
}

.empty-text {
  font-size: 14px;
  color: #787C8F;
  margin: 20px 0;
}

.drama-cards-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20px;
}

.drama-card {
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 16px;
  overflow: hidden;
}

.drama-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
}

.drama-card :deep(.el-card__body) {
  padding: 0;
}

.drama-card :deep(.el-card) {
  border-radius: 16px;
  overflow: hidden;
}

.drama-card-cover {
  height: 180px;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: relative;
  border-radius: 4px 4px 0 0;
  display: flex;
  align-items: flex-end;
}

.action-btn {
  font-size: 14px;
  color: #1F2329;
  cursor: pointer;
  border-radius: 8px;
  display: flex;
  flex: 1;
  height: 44px;
  justify-content: center;
  align-items: center;
  font-weight: 500;
}

.action-btn:hover {
  background: #f6f7f8;
}

.action-divider {
  width: 1px;
  height: 12px;
  background-color: rgba(31, 35, 41, 0.08);
}

.action-delete {
  color: #FC3333;
}

.drama-card-content {
  padding: 16px 14px 24px 14px;
  position: relative;
}

.drama-card-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  align-items: center;
  background-color: #FFFFFF;
  height: 87px;
  opacity: 0;
  transition: opacity 0.3s;
  gap: 6px;
  padding: 0 8px;
}

.drama-card:hover .drama-card-actions {
  opacity: 1;
}

.drama-card:hover .drama-name,
.drama-card:hover .drama-creator {
  visibility: hidden;
}

.drama-name {
  margin: 0 0 5px 0;
  font-size: 16px;
  font-weight: 500;
  color: #1C1D29;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.drama-creator {
  font-size: 12px;
  color: #95999E;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 创建剧本弹窗样式 */
.dialog-title {
  font-size: 16px;
  font-weight: 500;
  color: #1C1D29;
  line-height: 16px;
}

.form-label {
  font-weight: normal;
  font-size: 14px;
  font-weight: 500;
  color: var(--theme-color, #1C1D29);
}

.required-mark {
  color: #f56c6c;
  margin-left: 4px;
}

.cover-upload-container {
  width: 100%;
}

.cover-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.cover-uploader:hover {
  border-color: #409eff;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100px;
  width: 100px;
  background: #fff;
}

.upload-icon {
  font-size: 24px;
  color: #8c939d;
}

.upload-text {
  color: #525466;
  font-size: 14px;
  margin-top: 8px;
}

.cover-image {
  width: 100%;
  height: 178px;
  object-fit: cover;
  display: block;
}

.drama-file-uploader {
  width: 100%;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.drama-file-uploader:hover {
  border-color: #409eff;
}

.file-upload-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 16px 8px;
}

.file-upload-icon {
  width: 24px;
  height: 24px;
  margin-bottom: 12px;
}

.file-upload-text {
  font-size: 14px;
  color: #1C1D29;
  font-weight: 500;
  margin-bottom: 8px;
}

.file-upload-tip {
  font-size: 14px;
  color: #787C8F;
}

:deep(.el-upload-dragger) {
  width: 100%;
  background-color: transparent;
  border: none;
  height: 100%;
  padding: 0;
}

:deep(.el-upload) {
  height: 100%;
}

:deep(.el-progress__text) {
  display: flex;
  justify-content: center;
  width: 42px;
  min-width: 0;
  font-size: 12px !important;
  color: #0C63FA;
}

.circle-progress-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.drama-file-preview {
  display: flex;
  align-items: center;
  position: relative;
}

.drama-file-icon {
  width: 16px;
  height: 16px;
  margin-right: 8px;
}

.drama-file-name {
  font-size: 14px;
  color: #1C1D29;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.drama-remove-btn {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 自定义对话框样式 */
:deep(.drama-dialog .el-dialog__header) {
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
  margin-right: 0;
}

/* 自定义按钮样式，覆盖Element Plus默认样式 */
:deep(.el-button--primary) {
  background-color: var(--theme-color, #1C1D29);
  border-color: var(--theme-color, #1C1D29);
}

:deep(.el-button--primary:disabled) {
  background-color: var(--primary-disabled-color, #A2A6B8);
  border-color: var(--primary-disabled-color, #A2A6B8);
}

.page-title {
  color: #1C1D29;
  font-size: 16px;
  font-weight: 500;
  margin: 0;
}

/* 自定义删除确认弹窗 */
:deep(.delete-confirm-dialog .el-message-box__header) {
  display: none;
}

:deep(.delete-confirm-dialog .el-button--primary) {
  background-color: #FC3333 !important;
  border-color: #FC3333 !important;
  color: white !important;
}

:deep(.delete-confirm-dialog .el-button--primary:hover) {
  background-color: #fd5757 !important;
  border-color: #fd5757 !important;
}

:deep(.delete-confirm-button) {
  background-color: #FC3333;
  border-color: #FC3333;
}

:deep(.delete-confirm-button:hover) {
  background-color: #fd5757;
  border-color: #fd5757;
}

.dialog-footer {
  display: flex;
  width: 100%;
  align-items: center;
}

.flex-spacer {
  flex: 1;
}

.drama-card-cover-image {
  aspect-ratio: 9 / 16;
  object-fit: cover;
}

/* 新增的表单行样式 */
.form-row {
  display: flex;
  gap: 20px;
  /* 控制两个输入框之间的间距 */
  margin-bottom: 20px;
  /* 控制行之间的间距 */
}

/* 新增的表单项半宽样式 */
.form-item-half {
  flex: 1;
  /* 使每个表单项占据一半宽度 */
}

/* 剧本权限弹窗样式 */
.permission-dialog :deep(.el-dialog__header) {
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
  margin-right: 0;
}

.permission-content {
  min-height: 200px;
}

.permission-list {
  max-height: 400px;
  overflow-y: auto;
}

.permission-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
}

.permission-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.user-id {
  font-size: 12px;
  color: #787C8F;
}

.user-nickname {
  font-size: 14px;
  font-weight: 500;
  color: #1C1D29;
}

.drama-name {
  font-size: 12px;
  color: #787C8F;
}

.permission-actions {
  display: flex;
  gap: 8px;
}

.no-permissions {
  text-align: center;
  color: #787C8F;
  padding: 40px 0;
  font-size: 14px;
}

/* 用户搜索弹窗样式 */
.user-search-dialog :deep(.el-dialog__header) {
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
  margin-right: 0;
}

.user-search-content {
  min-height: 300px;
}

.user-search-content .el-input {
  margin-bottom: 16px;
}

.user-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.user-item:hover {
  background-color: #f8f9fa;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.user-info .user-id {
  font-size: 12px;
  color: #787C8F;
}

.user-info .user-nickname {
  font-size: 14px;
  font-weight: 500;
  color: #1C1D29;
}

.no-users {
  text-align: center;
  color: #787C8F;
  padding: 40px 0;
  font-size: 14px;
}

.permission-header {
  margin-bottom: 12px;
  display: flex;
  justify-content: flex-start;
  position: relative;
}

.permission-user-list {
  position: absolute;
  left: 0;
  top: 40px;
  width: 240px;
  background-color: #fff;
  border-radius: 6px;
  border: 1px solid rgba(162, 166, 184, 0.08);
  box-shadow: 0px 6px 12px 0px rgba(31, 35, 41, 0.08);
  z-index: 999;
  box-sizing: border-box;
}
</style>